const express = require('express')
const app = express()


const cors = require('cors')
const joi = require('joi')
const userRouter = require('./router/user')
const userInfoRouter = require('./router/userinfo')
const userArticleRouter = require('./router/article_cate')
const articleRouter = require('./router/articles')
app.use(cors())

const expressJwt = require('express-jwt')
const config = require('./config')


app.use(express.urlencoded({ extended: false }))

app.use(function(req, res, next) {
    res.cc = function(err, status = 1) {
        res.send({
            status,
            message: err instanceof Error ? err.message : err
        })
    }
    next()
})



app.use(expressJwt({ secret: config.jwtKey }).unless({ path: [/^\/api\//] }))

app.use('/api', userRouter)
app.use('/my', userInfoRouter)
app.use('/my', userArticleRouter)
app.use('/my', articleRouter)

app.use(function(err, req, res, next) {
    if (err instanceof joi.ValidationError) {
        res.cc(err)
    } else if (err.name === 'UnauthorizedError') {
        res.cc(`token 认证失败：${err.message}`, 4)
    } else {
        res.cc(err)
    }
    next()
})

app.listen(3007, function() {
    console.log('api server running at http://127.0.0.1:3007')
})